package com.tfjybj.itoo.exam.provider.controller;

import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.entity.ExamineeEntity;
import com.tfjybj.itoo.exam.model.ClassModel;
import com.tfjybj.itoo.exam.model.ExaminationModel;
import com.tfjybj.itoo.exam.model.ExaminationscoreModel;
import com.tfjybj.itoo.exam.model.ExamineeModel;
import com.tfjybj.itoo.exam.provider.service.ExamineeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


/**
 * ExamineeController
 * examinee表
 *
 * @author 任晓帅
 * @version 2.0.0
 * @since 2.0.0 2018-11-15 19:40:28
 */
@Api(tags = {"examinee表接口"})
@RequestMapping(value = "/examinee")
@RestController
@Slf4j
public class ExamineeController {

    @Resource
    private ExamineeService examineeService;

    //region 模板生成：基本增删改

    /**
     * 添加
     *
     * @param model ExamineeModel
     * @return 添加的结果
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "添加")
    @PostMapping(value = {"/create"})
    public ItooResult create(@RequestBody ExamineeModel model) {
        ExamineeEntity examineeEntity = new ExamineeEntity();
        BeanUtils.copyProperties(model, examineeEntity);
        examineeService.save(examineeEntity);
        return ItooResult.build(ItooResult.SUCCESS, "添加成功");
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return ItooResult 是否删除成功
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id删除（单个）")
    @DeleteMapping(value = {"/delete/{id}"})
    public ItooResult delete(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        examineeService.removeById(id);
        return ItooResult.build(ItooResult.SUCCESS, "删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return ItooResult 批量删除是否成功结果
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping(value = {"/deleteByIds"})
    @ApiImplicitParam(name = "ids", value = "ids", dataType = "List<String>", required = true)
    public ItooResult deleteByIds(@RequestBody List<String> ids) {
        examineeService.removeByIds(ids);
        return ItooResult.build(ItooResult.SUCCESS, "批量删除成功");
    }

    /**
     * 修改
     *
     * @param model ExamineeModel
     * @return 修改后的结果
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id修改examinee")
    @PutMapping(value = {"/modify"})
    public ItooResult modify(@RequestBody ExamineeModel model) {
        ExamineeEntity examineeEntity = new ExamineeEntity();
        BeanUtils.copyProperties(model, examineeEntity);
        examineeService.updateById(examineeEntity);
        return ItooResult.build(ItooResult.SUCCESS, "修改成功");
    }

    /**
     * 根据id查找Examinee
     *
     * @param id 主键id
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping(value = {"/findById/{id}"})
    public ItooResult findById(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        ExamineeEntity examineeEntity = examineeService.getById(id);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeEntity);
    }

    /**
     * 分页查询所有Examinee
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "分页查询所有Examinee")
    @GetMapping(value = {"/queryPageAll/{pageNo}/{pageSize}"})
    public ItooResult queryPageAll(@ApiParam(name = "pageNo", value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
                                   @ApiParam(name = "pageSize", value = "页数", required = true, example = "10") @PathVariable Integer pageSize) {
        PageInfo<ExamineeEntity> examinees = examineeService.queryPageAll(pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examinees);
    }

    /**
     * 根据学生姓名模糊查询examinee
     *
     * @param studentName 学生姓名
     * @param pageNo      页码
     * @param pageSize    页数
     * @return 模糊查询的examinee
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据学生姓名模糊查询examinee", notes = "分页根据学生姓名模糊查询examinee")
    @GetMapping(value = "queryExamineeByLikeStudentName/{pageNo}/{pageSize}")
    public ItooResult queryExamineeByLikeStudentName(@RequestParam(required = false, defaultValue = "") String studentName,
                                                     @ApiParam(name = "pageNo", value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
                                                     @ApiParam(name = "pageSize", value = "页数", required = true, example = "10") @PathVariable Integer pageSize) {
        PageInfo<ExamineeEntity> examineeList = examineeService.queryByLikeStudentName(studentName, pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeList);
    }
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */


    /**
     * 根据班级id和考试id批量导出班级所有学生成绩
     *
     * @param response http反应
     * @param exports  列表数据
     * @author 谢妞
     * @since 2018年12月14日19:23:16
     */
    @ApiOperation(value = "批量导出-根据班级id和考试id导出")
    @GetMapping(value = "/exportComplexByClassIdExamId")
    public void exportComplexByClassIdExamId(HttpServletResponse response, @RequestParam(value = "list") List<String> exports) {

        List<ExaminationModel> exportList = new ArrayList<>();
        ExaminationModel examinationModel = null;
        for (int i = 0; i < exports.size(); i++) {
            // 将考试ID和班级ID截取出来放到相应的list中
            if ((i % 2 + 2) % 2 != 0) {
                examinationModel.setExamId(exports.get(i));
                exportList.add(examinationModel);
            } else {
                examinationModel = new ExaminationModel();
                examinationModel.setClassId(exports.get(i));
            }
        }
        examineeService.exportComplexByClassIdExamId(response, exportList);
    }


    /**
     * 根据学生姓名模糊查询考生信息
     *
     * @param studentName 学生名字
     * @param classId     班级id
     * @return 班级本场考试所有成绩
     * @author 谢妞
     * @since 2018年12月14日19:23:16
     */
    @ApiOperation(value = "根据学生姓名模糊查询考生信息")
    @GetMapping(value = "/queryExamineLikeName/{studentName}/{classId}/{examId}")
    public ItooResult queryExamineLikeName(@PathVariable String studentName,
                                           @PathVariable String classId,
                                           @PathVariable String examId) {
        if (StringUtils.isEmpty(studentName)) {
            return ItooResult.build(ItooResult.FAIL, "考生姓名不能为空");
        }

        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeService.queryExamineLikeName(studentName, classId, examId));
    }

    /**
     * 根据考试班级ID和考试ID分页查询考生-已经完成
     *
     * @param classId 班级ID
     * @param examId  考试ID
     * @author 谢妞--魏恩君修改
     * @since 2018-11-24
     */
    @ApiOperation(value = "根据考试班级ID和考试ID分页查询考生")
    @GetMapping(value = "queryExamineByClassId/{classId}/{examId}")
    public ItooResult queryExamineByClassId(@ApiParam(name = "classId", value = "classId") @PathVariable String classId,
                                            @ApiParam(name = "examId", value = "examId") @PathVariable String examId) {

//        if (StringUtils.isEmpty(classId)) {
//            return ItooResult.build(ItooResult.FAIL, "班级ID不能为空");
//        }
        return ItooResult.build(ItooResult.SUCCESS, "查询班级考生成功", examineeService.queryPageExamineeByClassId(classId, examId));
    }


    /**
     * 根据考试ID获取所有考生成绩
     *
     * @param classId 班级ID
     * @param examId  考试ID
     * @author 魏恩君
     * @since 2019年2月22日09:27:14
     */
    @ApiOperation(value = "根据考试ID获取所有考生成绩")
    @GetMapping(value = "queryStudentScore")
    public ItooResult queryStudentScore(@RequestParam(required = false) String classId, @RequestParam(required = true) String examId) {
        return ItooResult.build(ItooResult.SUCCESS, "查询所有考生成绩成功", examineeService.queryPageExamineeByClassId(classId, examId));
    }


    /**
     * 导出单个班级的成绩信息
     *
     * @param classId 班级id
     * @param examId  考试id
     * @author 谢妞
     * @since 2018-11-28
     */
    @ApiOperation(value = "根据班级id和考试id导出班级学生成绩")
    @GetMapping(value = "/exportSingleScore/{classId}/{examId}")
    public ItooResult exportSingleScore(HttpServletResponse response, @ApiParam(name = "classId") @PathVariable String classId,
                                        @ApiParam(name = "examId", value = "examId") @PathVariable String examId) {
        return examineeService.exportSingleScore(response, classId, examId);
    }


    /**
     * 根据考试id查询查询课程信息
     *
     * @param examId 考试ID
     * @return
     */
    @ApiOperation(value = "根据考试id查询查询课程信息")
    @GetMapping(value = "/selExamClass/{examId}")
    public ItooResult selExamClass(@PathVariable String examId) {

        List<ClassModel> examModelList = examineeService.selExamClass(examId);
        if (examModelList.size() > 0) {
            return ItooResult.build(ItooResult.SUCCESS, "查询成功！", examModelList);
        } else {
            return ItooResult.build(ItooResult.FAIL, "查询失败");
        }
    }


    /**
     * 根据考试低查询考试下面所有的考生
     *
     * @param examinationId 考试id
     * @return 考生集合
     * @author 马莹
     * @since 2018-12-29 21:25:34
     */
    @ApiOperation(value = "根据考场id查询未考生信息")
    @GetMapping(value = "/selStudentInfo/{examinationId}")
    public ItooResult selStudentInfo(@PathVariable String examinationId) {
        if (StringUtils.isEmpty(examinationId)) {
            return ItooResult.build(ItooResult.FAIL, "考场id为空，不能进行查询！");
        }
        List<ExamineeModel> notExamStudentInfo = examineeService.selNotExamStudentInfo(examinationId);
        if (notExamStudentInfo != null) {
            return ItooResult.build(ItooResult.SUCCESS, "查询成功！", notExamStudentInfo);
        } else {
            return ItooResult.build(ItooResult.FAIL, "查询失败");
        }
    }

    /**
     * 于云秀-2018年12月11日
     * 根据学生id删除学生信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据学生id删除学生信息")
    @GetMapping(value = "/deleteStudentInfo/{id}")
    public ItooResult deleteStudentInfo(@PathVariable String id) {
        if (StringUtils.isEmpty(id)) {
            return ItooResult.build(ItooResult.FAIL, "学生id为空，不能进行查询");
        }
        try {
            examineeService.removeById(id);
            return ItooResult.build(ItooResult.SUCCESS, "删除成功！");
        } catch (Exception e) {
            return ItooResult.build(ItooResult.FAIL, "删除失败！");
        }
    }


    /**
     * 根据学号或姓名查询考生-模糊查询(考试信息管理)
     *
     * @author maying
     * @since 2018-12-11 10:14:16
     */
    @ApiOperation(value = "根据学号或姓名模糊查询学生")
    @GetMapping(value = "/queryStu/{examineeName}/{examinationId}")
    public ItooResult examineeName(@PathVariable String examineeName, @PathVariable String examinationId) {
        List<ExamineeModel> examineeModelList = examineeService.fuzzyQuery(examineeName, examinationId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功!", examineeModelList);
    }

    /**
     * 根据学生id查询差生信息,以及考试信息
     *
     * @param beginTime 考试开始时间
     * @param studentId 学生id
     * @param overTime  考试结束时间
     * @return 冲突考试的集合
     * @author 马莹
     * @since 2018-12-28 21:38:44
     */
    @ApiOperation(value = "根据学生id查询考生的信息,以及考试配置详情")
    @GetMapping(value = "/selectExaminee/{studentId}/{overTime}/{beginTime}")
    public ItooResult selectExaminee(@PathVariable String beginTime, @PathVariable String studentId, @PathVariable String overTime) {
        List<ExaminationModel> examinationModels = examineeService.selectExaminee(beginTime, overTime, studentId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功！", examinationModels);
    }

    /**
     * 根据考试id和学生id查询是否存在本场考试
     *
     * @param stuId  学生id
     * @param examId 考试id
     * @return 考生集合
     * @author 马莹
     * @since 2019-6-29 11:24:04
     */
    @ApiOperation(value = "根据考试id和学生id查询是否存在本场考试")
    @GetMapping(value = "/queryStuInExam/{stuId}/{examId}")
    public ItooResult queryStuInExam(@PathVariable String stuId, @PathVariable String examId) {
        Integer examIneeCout = examineeService.queryStuInExam(stuId, examId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examIneeCout);
    }

    /**
     * 导出Excel表格,分sheet,自定义表头
     *
     * @param examIdList 考试集合
     * @return 考生集合
     * @author 马莹
     * @since 2019-1-6 14:47:46
     */
    @ApiOperation(value = "导出Excel表格,分sheet,自定义表头")
    @GetMapping(value = "/customExportExcel")
    public void customExportExcel(@RequestParam List<String> examIdList, HttpServletRequest request,
                                  HttpServletResponse response) {
        examineeService.customExportExcel(examIdList, request, response);
    }

    /**
     * 根据考试id和班级id判断是否汇总过成绩
     *
     * @param examId
     * @param classId
     * @author 谢妞
     * @since 2019年1月13日21:00:25
     */
    @ApiOperation(value = "根据考试id和班级id判断是否汇总过成绩")
    @GetMapping(value = "/ifSummaryScore/{examId}/{classId}")
    public ItooResult ifSummaryScore(@PathVariable String examId, @PathVariable String classId) {
        int summary = examineeService.ifSummaryScore(examId, classId);
        if (summary > 0) {
            return ItooResult.build(ItooResult.SUCCESS, "已经汇总过！", summary);
        } else {
            return ItooResult.build(ItooResult.FAIL, "没有汇总过！", summary);
        }

    }

    /**
     * 根据教师id校验人数
     *
     * @param operator
     * @author 谢妞
     * @since 2019年1月20日08:30:16
     */
    @ApiOperation(value = "根据考试id校验人数")
    @GetMapping(value = "/checkExamine/{operator}")
    public ItooResult checkExamine(@PathVariable String operator) {
        if (StringUtils.isEmpty(operator)) {
            return ItooResult.build(ItooResult.FAIL, "教师Id为空,不能进行查询");
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeService.checkExamine(operator));
    }

    /**
     * 根据教师id查看缺考信息
     *
     * @param operator
     * @author 谢妞
     * @since 2019年1月22日16:07:19
     */
    @ApiOperation(value = "根据教师id查看缺考信息")
    @GetMapping(value = "/checkLack/{operator}")
    public ItooResult checkLack(@PathVariable String operator) {
        if (StringUtils.isEmpty(operator)) {
            return ItooResult.build(ItooResult.FAIL, "教师Id为空,不能进行查询");
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeService.checkLack(operator));
    }

    /**
     * 根据教师id查看没有成绩的学生
     *
     * @param operator 教师id
     * @param type     类型
     * @author 谢妞
     * @since 2019年1月22日16:38:03
     */
    @ApiOperation(value = "根据教师id查看没有成绩的考生")
    @GetMapping(value = "/checkNoScore/{operator}/{type}")
    public ItooResult checkNoScore(@PathVariable String operator, @PathVariable Integer type) {
        if (StringUtils.isEmpty(operator)) {
            return ItooResult.build(ItooResult.FAIL, "教师Id为空,不能进行查询");
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeService.checkNoScore(operator, type));
    }

    /**
     * 根据考生id和班级id查询各章节得分率60%以上人数
     *
     * @param classId
     * @param examId
     * @author a孙博雅
     * @sinces 2019年3月3日19:34:14
     */
    @ApiOperation(value = "根据考生id和班级id查询各章节得分率60%以上人数")
    @GetMapping(value = "queryhapternumbe/{classId}/{examId}")
    public ItooResult querychapternumbe(
            @ApiParam(value = "班级id ", required = true) @PathVariable String classId,
            @ApiParam(value = "考试id ", required = true) @PathVariable String examId) {
        if (StringUtils.isEmpty(classId)) {
            log.error("成绩分析--章节图-班级ID不能为空");
            return ItooResult.build(ItooResult.FAIL, "班级ID不能为空");
        }
        if (StringUtils.isEmpty(examId)) {
            return ItooResult.build(ItooResult.FAIL, "考试ID不能为空");
        }
        //根据班级id和考试id查询考生
        List<ExaminationModel> examinationModel = examineeService.queryStudent(classId, examId);
        ArrayList<ExaminationModel> examinationModels = new ArrayList<ExaminationModel>();
        List<ExaminationModel> examinationModelNew = new ArrayList<ExaminationModel>();

        if (examinationModel.size() > 0) {
            for (ExaminationModel em : examinationModel) {
                examinationModels.addAll(examineeService.querychapternumbe(classId, examId, em.getExamineeId()));
            }
            //多字段分组求和：分组
            Map<String, List<ExaminationModel>> collect = examinationModels.stream().collect(
                    Collectors.groupingBy(e -> fetchGroupKey(e)));
            for (ExaminationModel am : examinationModels) {
                List<ExaminationModel> sumPercent = collect.get(am.getChapterName());
                //求和
                int total = sumPercent.stream().mapToInt(
                        ExaminationModel::getPercent).sum();
                //赋值
                ExaminationModel chapterInformation = new ExaminationModel();
                chapterInformation.setChapterName(sumPercent.get(0).getChapterName());
                chapterInformation.setPercent(total);
                examinationModelNew.add(chapterInformation);
                //去重
                examinationModelNew = examinationModelNew.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(ExaminationModel::getChapterName))), ArrayList::new));
            }
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examinationModelNew);
    }

    private static String fetchGroupKey(ExaminationModel examinationModel) {
        return examinationModel.getChapterName();
    }

    /**
     * 根据考生id和班级id查询学生章节具体分数
     *
     * @param classId
     * @param examId
     * @author a孙博雅
     * @sinces 2019年3月16日20:43:36
     */
    @ApiOperation(value = "根据考生id和班级id查询学生章节具体分数")
    @GetMapping(value = "querychapterscore/{classId}/{examId}")
    public ItooResult querychapterscore(
            @ApiParam(value = "班级id ", required = true) @PathVariable String classId,
            @ApiParam(value = "考试id ", required = true) @PathVariable String examId) {
        if (StringUtils.isEmpty(classId)) {
            return ItooResult.build(ItooResult.FAIL, "班级ID不能为空");
        }
        if (StringUtils.isEmpty(examId)) {
            return ItooResult.build(ItooResult.FAIL, "考试ID不能为空");
        }
        //根据班级id和考试id查询考生
        List<ExaminationModel> studentModel = examineeService.queryStudent(classId, examId);
        List<ExaminationModel> examinationModels = new ArrayList<>();
        if (studentModel.size() > 0) {
            for (ExaminationModel em : studentModel) {
                ExaminationModel totalScore = new ExaminationModel();
                List<ExaminationscoreModel> scoreModelList = new ArrayList<>();
                //拼接两个model
                //学生姓名，章节名称，总分数
                totalScore = examineeService.selectTotalScore(classId, examId, em.getExamineeId());
                //章节id，章节名称，章节分数
                List<ExaminationModel> chapterScore = examineeService.querychapterscore(classId, examId, em.getExamineeId());
                for (ExaminationModel accepttemp : chapterScore) {
                    ExaminationscoreModel scoreModel = new ExaminationscoreModel();
                    if (totalScore.getStudentId().equals(accepttemp.getStudentId())) {
                        scoreModel.setChapterId(accepttemp.getChapterId());
                        scoreModel.setChapterscore(accepttemp.getChapterScore());
                        scoreModel.setChapterName(accepttemp.getChapterName());
                        scoreModelList.add(scoreModel);
                    }
                    totalScore.setExaminationScoreModelList(scoreModelList);
                    examinationModels.add(totalScore);
                }
            }
            //去重
            examinationModels = examinationModels.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                    () -> new TreeSet<>(Comparator.comparing(ExaminationModel::getStudentName))), ArrayList::new));
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examinationModels);

    }

    /**
     * 根据考试班级ID和考试ID分页查询考生
     *
     * @param classId 班级ID
     * @param examId  考试ID
     * @author 孙博雅
     * @since 2019年4月18日
     */
    @ApiOperation(value = "根据考试班级ID和考试ID分页查询考生")
    @GetMapping(value = "queryExamineByClassIdsby/{classId}/{examId}")
    public ItooResult queryExamineByClassIdsby(
            @ApiParam(name = "classId", value = "classId") @PathVariable String classId,
            @ApiParam(name = "examId", value = "examId") @PathVariable String examId) {
        return ItooResult.build(ItooResult.SUCCESS, "查询班级考生成功", examineeService.queryPageExamineeByClassIdsby(classId, examId));
    }

    /**
     * 根据考试id和班级id查询考生
     *
     * @param examinationId
     * @param classId
     * @author 樊建华
     * @sinces 2019年3月29日16:24:21
     */
    @ApiOperation(value = "根据考试id和班级id查询考生")
    @GetMapping(value = "/queryChapterNumbe/{examinationId}/{classId}")
    public ItooResult queryChapterNumbe(
            @ApiParam(value = "班级id ") @PathVariable String classId,
            @ApiParam(value = "考试id ") @PathVariable String examinationId) {
        List<ExamineeModel> examineeModelList = examineeService.queryChapterNumbe(examinationId, classId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", examineeModelList);
    }


    /**
     * 根据考试开始时间查询这个时间点有考试的考生
     *
     * @param examStartTime 考试开始时间
     * @return 考生集合
     * @author 马莹
     * @since 2019年3月28日19:47:46
     */
    @ApiOperation(value = "根据考试开始时间查询这个时间点有考试的考生")
    @GetMapping(value = "/queryExaminee/{examStartTime}")
    public ItooResult queryExaminee(@PathVariable String examStartTime) {
        List<ExamineeModel> examineeModelList = examineeService.queryExaminee(examStartTime);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功!", examineeModelList);
    }

}